package de.scs.core;

import java.util.LinkedList;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.stream.StreamSource;

public class BloodSugarParser implements IParser
{

  private List<Integer> bsvList  = new LinkedList<Integer>();
  private boolean       validXML = false;

  @Override
  public Object parseFile(String uri)
  {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader;
    try
    {
      eventReader = inputFactory.createXMLEventReader(new StreamSource(uri));

      XMLEvent event = eventReader.nextEvent();
      if (!validXML)
      {
        if (!event.isStartDocument())
        {
          System.err.println("Invalid XML file. No start header found");
          return null;
        }
        else
          validXML = !validXML;
      }
      event = eventReader.nextEvent();
      if (event.isStartElement())
      {
        if (event.asStartElement().getName().getLocalPart() != ("BloodSugarLevel"))
        {
          System.err.println("Malformed XML file.Expected root tag <BloodSugarLevel>");
          return null;
        }
        else
        {
          while (eventReader.hasNext())
          {

            event = eventReader.nextEvent();
            if (event.isStartElement())
            {
              if (event.asStartElement().getName().getLocalPart().contains("BloodSugarValue"))
              {
                event = eventReader.nextEvent();
                String val = "";
                if (event.isCharacters())
                {
                  try
                  {
                    val = event.asCharacters().getData().trim();
                    int bsv = Integer.parseInt(val);
                    if (bsv >= 20 && bsv <= 250) bsvList.add(bsv);
                    else System.err.println(bsv + " is not an allowed value.skipped.");
                  }
                  catch (NumberFormatException ne)
                  {
                    System.err.println(val + " is not a number.skipped");
                  }
                }
              }
            }
            continue;
          }
        }
      }
    }
    catch (XMLStreamException e)
    {
      e.printStackTrace();
    }
    return bsvList;
  }
}
